package com.epoch.base.oss;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

import org.apache.commons.lang.StringUtils;

import com.aliyun.oss.OSSClient;
import com.epoch.base.util.DateUtils;

public class AliyunCloudStorageService {
	
	private OSSClient client;
	
	CloudStorageConfig config;

    public AliyunCloudStorageService(CloudStorageConfig config) {
        this.config = config;
        //初始化
        init();
    }

    private void init() {
        client = new OSSClient(config.getAliyunEndPoint(), config.getAliyunAccessKeyId(),
                config.getAliyunAccessKeySecret());
    }
    
    public String upload(InputStream inputStream, String path) {
        try {
            client.putObject(config.getAliyunBucketName(), path, inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return config.getAliyunDomain() + path;
    }
    
    public String upload(File file) {
    	String path = "";
        try {
        	String prefix = file.getName().substring(file.getName().lastIndexOf(".") + 1);
        	InputStream inputStream = new FileInputStream(file);
        	path = getPath(config.getAliyunPrefix()) + "." + prefix;
            client.putObject(config.getAliyunBucketName(),path,inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return config.getAliyunDomain() + "/" + path;
    }
    
    public String upload(byte[] data, String path) {
        return upload(new ByteArrayInputStream(data), path);
    }
    
    public String getPath(String prefix) {
        //生成uuid
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        //文件路径
        String path = DateUtils.format(new Date(), "yyyyMMdd") + "/" + DateUtils.format(new Date(), "HHmmssS") + uuid.substring(0, 5);

        if (StringUtils.isNotBlank(prefix)) {
            path = prefix + "/" + path;
        }
        return path;
    }
}
